<?php

class CourseController extends SiteController
{
	/**
	 * @var organization
	 */
	protected $orgs;
	/**
	 * @var org
	 */
	protected $org;
	/**
	 * @var pm
	 */
	protected $pm;
	/**
	 * @var int
	 */
	protected $inboxUnread;
	/**
	 * @var adminModel
	 */
	protected $adminModel;
	/**
	 *
	 * @var $memberModel
	 */
	protected $memberModel;
	/**
	 *
	 * @var boolean
	 */
	protected $iAmAdmin;
	/**
	 *
	 * @var boolean
	 */
	protected $iAmMember;
	/**
	 *
	 * @var boolean
	 */
	protected $iAmBanned;

	/**
	 * vars for view population
	 * @var array 
	 */
	protected $templateVars;

	public function __construct() {
		$this->session();
		$this->orgs = new organization();
		$this->org = $this->orgs->getOrgByName( $name );
		$this->pm = new pm();
		$this->inboxUnread = $this->pm->countUnread( $_SESSION['stud_no'] );
		$this->adminModel = new admin();
		$this->memberModel = new member();
		$this->iAmAdmin = $this->adminModel->amIAdmin( $_SESSION['stud_no'], $this->org[0]['org_id'] );
		$this->memberModel->updateLastVisit($_SESSION['stud_no'], $this->org[0]['org_id']);
		$this->iAmMember = $this->memberModel->amIMember( $_SESSION['stud_no'], $name );
		$this->iAmBanned = $this->memberModel->amIBanned( $_SESSION['stud_no'], $this->org[0]['org_id'] );
		if( $this->iAmBanned ) $this->iAmMember = false;
		if( $this->iAmAdmin ) $this->iAmMember = true;
		if( $_SESSION['admin'] == '1' ) $this->iAmMember = true;
		if( $_SESSION['admin'] == '1' ) $this->iAmAdmin = true;
	}


	public function view( $name = NULL, $section = NULL, $action = NULL, $param = null, $param2 = null )
	{
		if( count( $this->org ) === 0 ) {
			$this->templateVars = array(
				'title' =>  'FEELS',
				'heading' => 'Sorry',
				'content' => 'The course with that name was not found.'
			);
		}
		else {
			if( $section === NULL ) {
				$this->org = $this->orgs->getOrgByName( $name );
				$this->templateVars =  array(
					'title' =>  $this->org[0]['description'] .' - FEELS ',
					'heading' => $this->org[0]['description'],
					'content' =>
						'<h2 class="heading">Home</h2>'
						. '<div class="homepage">'
						. '<div class="summary">'. nl2br( $this->org[0]['long_description'] ) . '</div>'
						. '<div class="description" style="margin-bottom: 10px;">'
						. "<img class=\"orglogo\" src=\"/photos/$name.jpg\">"
						. nl2br( $this->org[0]['info'] ) . '</div>'
						. ( $this->iAmAdmin ? "<a href=\"/org/view/$name/edit-info\">Edit Info</a> " : '' )
						. ( $this->iAmAdmin ? "<a href=\"/org/view/$name/edit-logo\">Change Logo</a> " : '' )
						. '</div>',
					'highlight' => 'orginfo',
					'currentOrg' => $name
				);
			}
			elseif ( $section === 'announcements' ) {}
			elseif( $section === 'events' ) {
				$eventsModel = new event();
				if( $action === NULL ) {
					$events = $eventsModel->getEvent( $name );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Announcements - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'organnouncements',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/events',
							array(
								'currentOrg' => $name,
								// 'name' => $org['name'],
								// 'description' => $org['description'],
								// 'long_description' => $org['long_description'],
								// 'announcements' => $article,
								'events' => $events,
								'isAdmin' => $this->iAmAdmin
							)
						)->getBuffer()
					);
				}
				else if( $action === 'show' ) {
					$event = $eventsModel->getEventById( $param );
					$regModel = new registration();
					$event = $event[0];
					$event['isAdmin'] = $this->iAmAdmin;
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - View Event - FEELS ',
						'heading' => $this->org[0]['description'],
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/event',
								array_merge( $event, array('currentOrg' =>$name))
							)->getBuffer()

					);
					if( $this->iAmMember ) {
						$this->templateVars['content'] .= BufferedView::instance('org/event_registered',
								array(
									'registereds' => $regModel->getRegList( $event['event_id'] )
								)
						)->getBuffer();
						if( (strtotime($event['date'] ) - (6*60*60*24)) > gmmktime() ) {
							if( !$regModel->isRegistered( $_SESSION['stud_no'], $event['event_id'] ) ) {
								$this->templateVars['content'] .= BufferedView::instance('org/forms/register',
										array(
											'action'=> "/org/view/$name/events/register",
											'event_id'=> $event['event_id'],
											'org_id'=>$this->org[0]['org_id']
										)
								)->getBuffer();
							} else {
								$this->templateVars['content'] .= 'You have registered for this activity.';
							}
						}
						else {
							$this->templateVars['content'] .= 'Registration period has ended.';
						}
						$commentModel = new commentEvent();
						$comments = $commentModel->getComment($event['event_id']);
						$this->templateVars['content'] .= BufferedView::instance('org/comments',
								array(
									'comments'=>$comments,
									'isAdmin'=>$this->iAmAdmin,
									'orgname'=>$name,
									'section' => 'events'
								)
						)->getBuffer();
						$this->templateVars['content'] .= BufferedView::instance('org/forms/comment',
								array(
									'action' => "/org/view/$name/events/comment",
									'hiddenInputs' => array(
										'event_id' => $param
									)
								)
							)->getBuffer();
						if( $param2 === 'blankcomment' ) {
							$this->templateVars['content'] .= 'Do not leave the comment field blank';
						}
					}
				}
				else if( $action === 'comment' ) {
					if( !empty( $_POST['post'] ) ) {
						$commentModel = new commentEvent();
						$commentModel->insertComment ( $_POST['event_id'], $_SESSION['stud_no'], gmdate('Y-m-d H:i:s'), $_POST['post'] );
						header("Location: /org/view/$name/events/show/" . $_POST['event_id'] );
					}
					else {
						header("Location: /org/view/$name/events/show/" . $_POST['event_id'] . "/blankcomment" );
					}

				}
				elseif( $action === 'comment-delete' ) {
					$commentModel = new commentEvent();
					$commentModel->deleteComment( $param );
					header("Location: " . $_SERVER['HTTP_REFERER'] );
					//header("Location: /org/view/$name/events/show/" . $_POST['article_id']);
				}
				else if( $action === 'register' ) {
					$model = new registration();
					$register = $model->insertReg( $_POST['eventId'], $_POST['orgId'],$_SESSION['stud_no'] );
					$message = "You have been registered for this event.
					Click <a href=\"/org/view/$name/events/show/{$_POST['eventId']}\">here</a> to go back." ;
					$this->templateVars['content'] = $message;
				}
				else if( $action === 'add' ) {
					$orgModel = new organization();
					$orgId = $orgModel->getOrgId( $name );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Add Event - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgevents',
						'currentOrg' => $name,
						'content' =>
							($param === 'invalid' ? 'Please fill in all fields' : '' )
							. BufferedView::instance('org/forms/event',
							array(
								'action'=>"/org/view/$name/events/add-confirm",
								'hiddenInputs'=>array('org_id'=>$orgId)
							)
						)->getBuffer()
					);
				}
				else if( $action === 'add-confirm' ) {
					if( 	!empty($_POST['org_id']) &&
							!empty($_POST['name']) &&
							!empty($_POST['date']) &&
							!empty($_POST['fee']) &&
							!empty($_POST['venue']) &&
							!empty($_POST['description'])	) {
						try {
							$eventsModel->insertEvent(
								$_POST['org_id'],
								$_POST['name'],
								$_POST['date'],
								$_POST['starthour']. ':' .$_POST['startminute'],
								$_POST['endhour']. ':' .$_POST['endminute'],
								$_POST['fee'],
								$_POST['venue'],
								$_POST['description']
							);
							$this->templateVars =  array(
								'title' =>  $this->org[0]['description'] .' - Add Event - FEELS ',
								'heading' => $this->org[0]['description'],
								'currentOrg' => $name,
								'content' => 'Event has been posted. Click <a href="/org/view/' . $name . '/events">here</a> to go back to events.'
							);

						} catch( Exception $e ) {
							$this->templateVars =  array(
								'title' =>  $this->org[0]['description'] .' - Add Event - FEELS ',
								'heading' => $this->org[0]['description'],
								'currentOrg' => $name,
								'content' => 'There has been an error. ' . 	$e->getMessage()
							);
						}
					}
					else {
						header("Location: /org/view/$name/events/add/invalid");
					}
				}
				else if( $action === 'edit' ) {
					$event = $eventsModel->getEventById( $param );
					$event = $event[0];
					$stime = explode( ':', $event[0]['starttime'] );
					$etime = explode( ':', $event[0]['endtime'] );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Edit Event - FEELS ',
						'heading' => $this->org[0]['description'],
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/forms/event',
							array(
								'action'=>"/org/view/$name/events/edit-confirm",
								'name'=> $event['Event'],
								'description'=> $event['description'],
								'date'=> $event['date'],
								'starthour'=> $stime[0],
								'startminute'=> $stime[1],
								'endhour'=> $etime[0],
								'endminute'=> $etime[1],
								'fee'=> $event['fee'],
								'venue'=> $event['venue'],
								'hiddenInputs'=>array('event_id'=>$param)
							)
						)->getBuffer()
					);
				}
				else if( $action === 'edit-confirm' ) {
					try {
						$eventsModel->updateEvent(
							$_POST['event_id'],
							$_POST['name'],
							$_POST['date'],
							$_POST['starthour'] .':'. $_POST['startminute'],
							$_POST['endhour'] .':'. $_POST['endminute'],
							$_POST['fee'],
							$_POST['venue'],
							$_POST['description']
						);
						$this->templateVars =  array(
							'title' =>  $this->org[0]['description'] .' - Edit Event - FEELS ',
							'heading' => $this->org[0]['description'],
							'currentOrg' => $name,
							'content' => 'Event has been updated. Click <a href="/org/view/' . $name . '/events">here</a> to go back to Events.'
						);
					}
					catch( Exception $e ) {
						$this->templateVars =  array(
							'title' =>  $this->org[0]['description'] .' - Edit Event - FEELS ',
							'heading' => $this->org[0]['description'],
							'currentOrg' => $name,
							'content' => 'There has been an error. ' . 	$e->getMessage()
						);
					}
				}
				else if( $action === 'delete' ) {
					$event = $eventsModel->getEventById( $param );
					$event = $event[0];
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Delete Event - FEELS ',
						'heading' => $this->org[0]['description'],
						'currentOrg' => $name,
						'content' => 'Are you sure you wish to delete the following event?'
							. BufferedView::instance('org/event',
								$event
							)->getBuffer()
							. BufferedView::instance('org/forms/confirm',
								array(
									'action' => "/org/view/$name/events/delete-confirm",
									'hiddenInputs' => array(
										'event_id' => $param
									)
								)
							)->getBuffer()
					);
				}
				else if( $action === 'delete-confirm' ) {
					try {
						if( $_POST['confirm-yes'] ) {
							$eventsModel->deleteEvent( $_POST['event_id'] );
							$this->templateVars =  array(
								'title' =>  $this->org[0]['description'] .' - Delete Event - FEELS ',
								'heading' => $this->org[0]['description'],
								'currentOrg' => $name,
								'content' => 'Event has been removed. Click <a href="/org/view/' . $name . '/events">here</a> to go back to events.'
							);
						}
						else {
							header("Location: /org/view/$name/events");
						}
					} catch( Exception $e ) {
						$this->templateVars =  array(
							'title' =>  $this->org[0]['description'] .' - Delete Announcement - FEELS ',
							'heading' => $this->org[0]['description'],
							'highlight' => 'organnouncements',
							'currentOrg' => $name,
							'content' => 'There has been an error. ' . 	$e->getMessage()
						);
					}
				}
				$this->templateVars['highlight'] = 'orgevents';
			}
			elseif( $section === 'tutorials' ) {
				$tutorialsModel = new tutorial();
				if( $action === NULL ) {
					$tutorials = $tutorialsModel->getTutorial( $name );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Tutorials - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgtutorial',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/tutorials',
							array(
								// 'name' => $org['name'],
								// 'description' => $org['description'],
								// 'long_description' => $org['long_description'],
								'tutorials' => $tutorials,
								'orgname' => $name,
								'isAdmin' => $this->iAmAdmin
								)
						)->getBuffer()
					);
				}
				elseif( $action === 'show' ) {
					$tutorial = $tutorialsModel->getTutorialById( $param );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Tutorials - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgtutorial',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/tutorial',
							array(
								'name' => $this->org['name'],
								'description' => $this->org['description'],
								'long_description' => $this->org['long_description'],
								'announcements' => $article,
								'tutorial' => $tutorial[0],
								'orgid' => $this->org[0]['org_id'],
								'orgname' => $name,
								'isAdmin' => $this->iAmAdmin
							)
						)->getBuffer()
					);
					if( $this->iAmMember ) {
						$commentModel = new commentTutorial();
						$comments = $commentModel->getComment($tutorial[0]['topic_id']);
						$this->templateVars['content'] .= BufferedView::instance('org/comments',
								array(
									'comments'=>$comments,
									'isAdmin'=>$this->iAmAdmin,
									'orgname'=>$name,
									'section' => 'tutorials'
								)
						)->getBuffer();
						$this->templateVars['content'] .= BufferedView::instance('org/forms/comment',
								array(
									'action' => "/org/view/$name/tutorials/comment",
									'hiddenInputs' => array(
										'topic_id' => $param
									)
								)
						)->getBuffer();
					}
					if( $param2 === 'blankcomment' ) {
						$this->templateVars['content'] .= 'Do not leave the comment field blank';
					}
				}
				else if( $action === 'comment' ) {
					if( !empty( $_POST['post'] ) ) {
						$commentModel = new commentTutorial();
						$commentModel->insertComment ( $_POST['topic_id'], $_SESSION['stud_no'], gmdate('Y-m-d H:i:s'), $_POST['post'] );
						header("Location: /org/view/$name/tutorials/show/" . $_POST['topic_id'] 	);
					}
					else {
						header("Location: /org/view/$name/tutorials/show/" . $_POST['topic_id'] .'/blankcomment' );
					}
				}
				elseif( $action === 'comment-delete' ) {
					$commentModel = new commentTutorial();
					$commentModel->deleteComment( $param );
					header("Location: " . $_SERVER['HTTP_REFERER'] );
					//header("Location: /org/view/$name/announcements/show/" . $_POST['article_id']);
				}
				elseif( $action === 'add' ) {
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Comment - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgtutorial',
						'currentOrg' => $name,
						'content' =>
							( $param === 'invalid' ? 'Please fill in all fields' : '' )
							. ( $param === 'fail' ? 'Could not upload' : '' )
							. BufferedView::instance('org/forms/tutorial', array(
							'action' => "/org/view/$name/tutorials/add-confirm"
						) )->getBuffer()
					);
				}
				elseif( $action === 'add-confirm' ) {
					if( !empty( $_POST['title'] ) && !empty( $_POST['description'] ) ) {
						$tutorialModel = new tutorial();
						$tutorialId = $tutorialModel->insertTutorial( $this->org[0]['org_id'], $_FILES['file']['name'], $_POST['title'], gmdate('Y-m-d H:i:s'), $_POST['description'] );
						if( end( explode('.', strtolower( $_FILES['file']['name'] ) ) ) === 'pdf' ) {
							if( !file_exists("./pdfs/{$this->org[0]['org_id']}") ) mkdir( "./pdfs/{$this->org[0]['org_id']}" );
							if( move_uploaded_file( $_FILES['file']['tmp_name'], "./pdfs/{$this->org[0]['org_id']}/$tutorialId.pdf" ) ) $uploadComplete = $tutorialModel->insertTutorialDone();
							else $uploadComplete = $tutorialModel->insertTutorialFail();
						}
						else {
							$uploadComplete = $tutorialModel->insertTutorialFail();
						}
						$this->templateVars =  array(
							'title' =>  $this->org[0]['description'] .' - Comment - FEELS ',
							'heading' => $this->org[0]['description'],
							'highlight' => 'orgtutorials',
							'currentOrg' => $name
						);
						if( $uploadComplete ) header("Location: /org/view/$name/tutorials/");
						else header("Location: /org/view/$name/tutorials/add/fail");
					}
					else header("Location: /org/view/$name/tutorials/add/invalid");
				}
				elseif( $action === 'edit' ) {

				}
				elseif( $action === 'edit-confirm' ) {

				}
				elseif( $action === 'delete' ) {
					$tutorial = $tutorialsModel->getTutorialById( $param );
					$this->templateVars =  array(
						'title' =>  $this->org[0]['description'] .' - Tutorial - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgtutorials',
						'currentOrg' => $name,
						'content' => "Are you sure you wish to delete this tutorial?"
						. BufferedView::instance('org/tutorial',
							array(
								'name' => $this->org['name'],
								'description' => $this->org['description'],
								'long_description' => $this->org['long_description'],
								'announcements' => $article,
								'tutorial' => $tutorial[0],
								'orgid' => $this->org[0]['org_id'],
								'orgname' => $name
							)
						)->getBuffer()
						. BufferedView::instance('org/forms/confirm', array(
							'action' => "/org/view/$name/tutorials/delete-confirm",
							'hiddenInputs' => array( 'topic_id' => $param, 'org_id'=>$this->org[0]['org_id'] )
						) )->getBuffer()
					);
				}
				elseif( $action === 'delete-confirm' ) {
					if( isset($_POST['confirm-yes'] ) ) {
						$file = "./pdfs/{$this->org[0]['org_id']}/{$_POST['topic_id']}.pdf";
						if( file_exists( $file ) ) unlink( $file ) ;
						$tutorialsModel->deleteTutorial( $_POST['topic_id'] );
						header("Location: /org/view/$name/tutorials/");

					}
					else header("Location: /org/view/$name/tutorials/");
				}
			}
			elseif( $section === 'memberlist' ) {
				$membersModel = new member();
				$members = $membersModel->getOrgMembersAdminByOrgName( $name );
				$this->templateVars =  array(
					'title' =>  $this->org[0]['description'] .' - Members - FEELS ',
					'heading' => $this->org[0]['description'],
					'highlight' => 'orgmember',
					'currentOrg' => $name,
				);
				$this->templateVars['content'] = '';
				if( $this->iAmAdmin ) {
					if( isset( $action ) && $action === 'add' ) {
						$already = $membersModel->isMember( $param, $this->org[0]['org_id'] );
						if( !$already ) {
							$membersModel->insertMember( $param, $this->org[0]['org_id'], gmdate('Y-m-d H:i:s'), 0 );
							$usermodel = new user();
							$pmmodel = new pm();
							$user = $usermodel->findUser($param);
							$mi = $user[0]['middlename']{0};
							$username = ucwords( strtolower( "{$user[0]['lastname']}, {$user[0]['firstname']} $mi." ));
							$subject = 'Notification of new membership';
							$message = "Student number: {$param}
	Attention, $username:
	You are now a member of {$this->org[0]['description']}.";
							$pmmodel->insertPm( $_SESSION['stud_no'], $param, gmdate('Y-m-d H:i:s'), $subject, $message );
							header("Location: /org/view/$name/memberlist");
						}

					}
					elseif( isset( $action ) && $action === 'remove' ) {
						if( $membersModel->isMember( $param, $this->org[0]['org_id'] ) ) $membersModel->deleteMember( $param, $this->org[0]['org_id'] );
						header("Location: /org/view/$name/memberlist");
					}
					elseif( isset( $action ) && $action === 'ban' ) {
						if( $membersModel->isMember( $param, $this->org[0]['org_id'] ) ) $membersModel->ban( $param, $this->org[0]['org_id'] );
						header("Location: /org/view/$name/memberlist");
					}
					elseif( isset( $action ) && $action === 'unban' ) {
						if( $membersModel->isMember( $param, $this->org[0]['org_id'] ) ) $membersModel->unban( $param, $this->org[0]['org_id'] );
						header("Location: /org/view/$name/memberlist");
					}
					if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
						$userModel = new user();
						$result = $userModel->findUser( $_POST['search'] );
						if( count( $result ) > 0  ) {
							$result = $result[0];
							$nohits = NULL;

						}
						else {
							$result = NULL;
							$result = NULL;
							$nohits = $_POST['search'];
						}
					}
					$this->templateVars['content'] .= BufferedView::instance('org/forms/find_member', array(
						'name' => $name,
						'result' => $result,
						'already' => $already,
						'nohits' => $nohits
					) )->getBuffer();
				}

				$this->templateVars['content'] .= BufferedView::instance('org/memberlist',
					array(
						'name' => $name	,
						// 'description' => $org['description'],
						// 'long_description' => $org['long_description'],
						'members' => $members,
						'orgAdmin' => $this->iAmAdmin
					)
				)->getBuffer();
			}
			elseif( $section === 'ban' ) {
				$this->templateVars['currentOrg'] = $name;
				$this->templateVars['content'] .= BufferedView::instance('org/forms/banning',
					array(
						'action'=> "/org/view/$name/ban-confirm",
						'hiddenInputs' => array(
							'stud_no' => $action
						)
					)
				)->getBuffer();
			}
			elseif( $section === 'ban-confirm' ) {
				if( $_POST['confirm-yes'] && !empty( $_POST['reason'] ) ) {
					$membermodel = new member();
					$membermodel->ban( $_POST['stud_no'], $this->org[0]['org_id'] );
					$usermodel = new user();
					$user = $usermodel->findUser($_POST['stud_no']);
					$admins = $usermodel->getSiteAdmin();
					$model = new pm();
					$bannedmi = $user[0]['middlename']{0};
					$banneduser = ucwords( strtolower( "{$user[0]['lastname']}, {$user[0]['firstname']} $bannedmi." ));
					$reason = $_POST['reason'];
					$subject = 'Notification for banning';
					$message = "Student number: {$_POST['stud_no']}
	$banneduser is being banned for reason:

	$reason
					";
					$model->insertPm( $_SESSION['stud_no'], $_POST['stud_no'], gmdate('Y-m-d H:i:s'), $subject, $message );
					foreach( $admins as $admin) {
						$model->insertPm( $_SESSION['stud_no'], $admin['stud_no'], gmdate('Y-m-d H:i:s'), $subject, $message );
					}
				}
				elseif( $_POST['confirm-no'] ) {

				}
				header("Location: /org/view/$name/memberlist");
			}
			elseif( $section === 'forum' ) {
				$model = new forum();
				$orgForums = $model->getForums($name);
				if( $action === NULL )
				{
					$this->templateVars =  array(
						'title' => 'Forums - FEELS',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgforum',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/forums',array(
							"forums" => $orgForums,
							'orgname' => $name,
							'isAdmin' => $this->iAmAdmin,
						) )->getBuffer()
					);
				}
				if( $action === 'view' )
				{
					$threads = $model->getThreads($param);

					$this->templateVars =  array(
						'title' =>  'Forums - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgforum',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/threads',array(
							"threads" => $threads,
							'orgname' => $name,
							'forumid' => $param,
							'isAdmin' => $this->iAmAdmin,
							'isMember' => $this->iAmMember
						) )->getBuffer()
					);
				}
				elseif( $action === 'new' ) {
					$this->templateVars =  array(
						'title' =>  'Forums - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgforum',
						'currentOrg' => $name,
						'content' =>
							( $param === 'invalid' ? 'Please fill in all fields' : '' )
							. BufferedView::instance('org/forms/forum',array(
							"action" => "/org/view/$name/forum/new-confirm"
						) )->getBuffer()
					);
				}
				elseif( $action === 'new-confirm' ) {
					if( !empty( $_POST['name'] ) ) {
						$forum = $model->insertForum( $this->org[0]['org_id'], $_POST['name'], $_POST['description'], gmdate('Y-m-d H:i:s'), 0, NULL );
						header("Location: /org/view/$name/forum");
					}
					else {
						header("Location: /org/view/$name/forum/new/invalid");
					}
				}
				elseif( $action === 'edit' ) {
					$forum = $model->getForum($param);
					$this->templateVars =  array(
						'title' =>  'Forums - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgforum',
						'currentOrg' => $name,
						'content' => BufferedView::instance('org/forms/forum',array(
							"action" => "/org/view/$name/forum/edit-confirm/$param",
							"name" => $forum['title'],
							"description" => $forum['description']
						) )->getBuffer()
					);
				}
				elseif( $action === 'edit-confirm' ) {
					if( !empty( $_POST['name'] ) ) $forum = $model->updateForum($_POST['name'], $_POST['description'], $param);
					header("Location: /org/view/$name/forum");
				}
				elseif( $action === 'delete' ) {
					$forum = $model->getForum($param);
					$this->templateVars =  array(
						'title' =>  'Forums - FEELS ',
						'heading' => $this->org[0]['description'],
						'highlight' => 'orgforum',
						'currentOrg' => $name,
						'content' => 'Are you sure you wish to delete this forum?'
							. BufferedView::instance('org/forum', array(
								'row' => $forum,
							))->getBuffer()
							. BufferedView::instance('public/forms/confirm', array(
								'action' => "/org/view/$name/forum/delete-confirm/$param",
								'hiddenInputs' => array()
							))->getBuffer()
					);
					$output .= BufferedView::instance('org/forum', array(
						'row' => $forum,
					))->getBuffer();
					$output .= BufferedView::instance('public/forms/confirm', array(
						'action' => "/org/view/$name/forum/delete-confirm/$param",
						'hiddenInputs' => array()
					))->getBuffer();
				}
				elseif( $action === 'delete-confirm' ) {
					if( $_POST['confirm-yes'] ) {
						$model->deleteForum($param);
						header("Location: /org/view/$name/forum");
					}
					elseif( $_POST['confirm-no'] ) {
						$forum = $model->lookupThreadForum($param);
						header("Location: /org/view/$name/forum");
					}
				}

			}
			elseif( $section === 'thread' ) {
				$this->session();
				$model = new forum();
				if( $action === 'view' ) {
					$post = $model->getPosts($param);
					$forum = $model->lookupThreadForum($param);
					$model->updateThreadViews($param);
					$output = BufferedView::instance('org/posts',array(
						"posts" => $post,
						'orgname' => $name,
						'forum' => $forum,
						'isAdmin' => $this->iAmAdmin,
						'isMember' => $this->iAmMember
					) )->getBuffer();
					if( $param2 === 'invalid' ) $output .= 'Please enter a post';
				}
				elseif( $action === 'new' ) {
					if( isset( $param ) && $param !== 'confirm' ) {
						$output = '';
						if( $param2 === 'invalid' ) $output = 'Please fill in all fields';
						$output .= BufferedView::instance('org/forms/thread', array(
							'action' => "/org/view/$name/thread/new/confirm",
							'hiddenInputs' => array( 'forum_id' => $param )
						) )->getBuffer();
					}
					elseif( $param === 'confirm' ) {
						try {
							if( !empty( $_POST['topic'] ) ) {
								$model->insertThread( $_POST['forum_id'], $_POST['topic'], $_SESSION['stud_no'], gmdate('Y-m-d H:i:s'), 0, 0, null, $_POST['post'] );
								header("Location: /org/view/$name/forum/view/{$_POST['forum_id']}");
							}
							else {
								header("Location: /org/view/$name/thread/new/{$_POST['forum_id']}/invalid");
							}
						} catch( Exception $e ) {
							$output = 'There has been an error.';
						}
					}
				}
				elseif( $action === 'edit' ) {
				}
				elseif( $action === 'delete' ) {
					$thread = $model->getThread($param);
					$output = 'Are you sure you wish to delete this thread?';
					$output .= BufferedView::instance('org/thread', array(
						'thread' => $thread,
					))->getBuffer();
					$output .= BufferedView::instance('public/forms/confirm', array(
						'action' => "/org/view/$name/thread/delete-confirm/$param",
						'hiddenInputs' => array()
					))->getBuffer();
				}
				elseif( $action === 'delete-confirm' ) {
					if( $_POST['confirm-yes'] ) {
						$forum = $model->lookupThreadForum($param);
						$model->deleteThread($param);
						header("Location: /org/view/$name/forum/view/$forum");
					}
					elseif( $_POST['confirm-no'] ) {
						$forum = $model->lookupThreadForum($param);
						header("Location: /org/view/$name/forum/view/$forum");
					}
					$output = 'Are you sure you wish to delete this thread?';
					$output .= BufferedView::instance('org/thread', array(
						'thread' => $thread,
					))->getBuffer();
					$output .= BufferedView::instance('public/forms/confirm', array(
						'action' => "/org/view/$name/forum/delete-confirm/$param",
						'hiddenInputs' => array()
					))->getBuffer();
				}
				$this->templateVars =  array(
					'title' =>  'Thread - FEELS ',
					'heading' => $this->org[0]['description'],
					'highlight' => 'orgforum',
					'currentOrg' => $name,
					'content' => $output
				);
			}

			elseif( $section === 'post' ) {
				$this->session();
				if( !empty( $_POST['message'] ) ) {
					$model = new forum();
					$date = gmdate ( 'Y-m-d H:i:s' );
					$post = $model->insertPost($_POST['threadId'],$_SESSION['stud_no'], $date, $_POST['message'] );
					header("Location: /org/view/$name/thread/view/{$_POST['threadId'] }");
				}
				else {
					header("Location: /org/view/$name/thread/view/{$_POST['threadId']}/invalid");
				}
			}
			elseif( $section === 'edit-post' ) {
				$this->session();
				$this->templateVars =  array(
					'title' =>  'Post - FEELS ',
					'heading' => $this->org[0]['description'],
					'highlight' => 'orgforum',
					'currentOrg' => $name,
					'content' => BufferedView::instance('org/edit_post',array(
						"message" => $_POST['message'],
						"postId" => $_POST['postId'],
						"threadId" => $_POST['threadId'],
						'orgname' => $name
					) )->getBuffer()
				);
			}
			elseif( $section === 'edit-post-confirm' ) {
				$this->session();
				$model = new forum();
				$post = $model->updatePost($_POST['message'],$_POST['postId'] );
				header("Location: /org/view/$name/thread/{$_POST['threadId'] }");
			}
			elseif( $section === 'delete-post' ) {
				$this->session();
				$model = new forum();
				$post = $model->getPost( $action );
				$post = $post[0];
				$this->templateVars =  array(
					'title' =>  'Post - FEELS ',
					'heading' => $this->org[0]['description'],
					'highlight' => 'orgforum',
					'currentOrg' => $name,
					'content' => 'Are you sure you wish to delete the following post?'
					. BufferedView::instance('org/post',array(
						"row" => $post,
						"postId" => $_POST['postId'],
						"threadId" => $_POST['threadId'],
						'orgname' => $name
					) )->getBuffer()
					. BufferedView::instance('public/forms/confirm',array(
						"action" => "/org/view/$name/delete-post-confirm",
						"message" => $_POST['message'],
						"threadId" => $_POST['threadId'],
						'hiddenInputs' => array(
							"postId" => $action,
							'referrer' => $_SERVER['HTTP_REFERER']
						),
						'orgname' => $name
					) )->getBuffer()
				);
			}
			elseif( $section === 'delete-post-confirm' ) {
				$this->session();
				if( $_POST['confirm-yes'] ) {
					$model = new forum();
					$post = $model->deletePost( $_POST['postId']);
					header("Location: " . $_POST['referrer'] );
				}
				elseif( $_POST['confirm-no'] ) {
					header("Location: " . $_POST['referrer'] );
				}
				//header("Location: /org/view/$name/thread/{$_POST['threadId'] }");
			}
			elseif( $section === 'photos') {
				$this->session();
				$orgid = $this->org[0]['org_id'];
				if( $action === NULL || $action === 'oversize' || $action === 'notimage' ) {
					$oldpath = getcwd();
					$path = "./photos/$orgid/";
					if( file_exists($path) && is_dir($path) ) {
						chdir($path);
						$files = glob("*");
						$totalsize = 0;
						foreach( (array) $files as $file ) {
							$totalsize += filesize( $file );
						}
						$totalsize = sprintf("%.2f", $totalsize / 1048576);
						$output .= "<h2 class=\"heading\">Org graphics</h2>";
						if( $action === 'oversize' ) $output .= "<div style=\"font-weight: bold;\">file uploaded would go over the limit</div>";
						if( $action === 'notimage' ) $output .= "<div style=\"font-weight: bold;\">file uploaded is not an image</div>";
						$output .= "$totalsize MB of 3 MB";
						$output .= "<div>Images only</div>	";
						$output .= '<form enctype="multipart/form-data" method="post" action="/org/view/'.$name.'/photos/add"><input type="file" name="file" /><input type="submit" value="Upload" /></form>';
						$output .= '<ul style="margin-left: 20px;"	>';
						if( $files !== false ) foreach( (array)$files as $filename) {
							$output .=  "<li>$filename(<a href=\"/photos/$orgid/$filename\">View</a>)(<a href=\"/org/view/$name/photos/delete/$filename\">Delete</a>)</li>\n";
						}
						$output .= '</ul>';
						chdir($oldpath);
					}
					else {
						$output .= 'Directory is not available for upload.';
					}
					$this->templateVars = array(
						'heading' => $this->org[0]['description'],
						'content' => $output,
						'currentOrg' => $name
					);
				}
				elseif( $action === 'add' ) {
					$oldpath = getcwd();
					$path = "./photos/$orgid/";
					if( file_exists($path) && is_dir($path) ) {
						chdir($path);
						$files = glob("*");
						$totalsize = 0;
						foreach( (array) $files as $file ) {
							$totalsize += filesize( $file );
						}
						chdir($oldpath);
						if( $totalsize + $_FILES['file']['size'] > 3*1048576 ) {
							header("Location: /org/view/$name/photos/oversize");
						}
						else {
							$info = getimagesize( $_FILES['file']['tmp_name'] );
							if( $info === false ) header("Location: /org/view/$name/photos/notimage");
							elseif( move_uploaded_file( $_FILES['file']['tmp_name'], "./photos/$orgid/" . $_FILES['file']['name'] ) ) {
								header("Location: /org/view/$name/photos");
							}
						}
					}

				}
				elseif( $action === 'delete' ) {
					$output = "<h2 class=\"heading\">Delete</h2>";
					$oldpath = getcwd();
					$path = "./photos/$orgid/";
					if( file_exists($path) && is_dir($path) ) {
						chdir($path);
						if( file_exists( $param ) ) {
							$output .= "Are you sure you want to delete $param?";
						}
						chdir($oldpath);
					}
					$this->templateVars = array(
						'heading' => $this->org[0]['description'],
						'content' => $output
						. BufferedView::instance('public/forms/confirm', array(
							'action' => "/org/view/$name/photos/delete-confirm/$param",
							'hiddenInputs' => array()
						))->getBuffer()
					);
				}
				elseif( $action === 'delete-confirm' ) {
					$oldpath = getcwd();
					$path = "./photos/$orgid/";
					if( file_exists($path) && is_dir($path) ) {
						chdir($path);
						if( file_exists($param) ) unlink( $param );
						chdir($oldpath);
						header("Location: /org/view/$name/photos");
					}
					else {
						echo 'file dne';
					}
				}
				$this->templateVars['highlight'] = 'orggraphics';
			}
			elseif( $section === 'memberlist' ) {
				$membersModel = new member();
				$members = $membersModel->getOrgMembersByOrgName( $name );
				$this->templateVars =  array(
					'title' =>  $this->org[0]['description'] .' - Members - FEELS ',
					'heading' => $this->org[0]['description'],
					'highlight' => 'orgmember',
					'currentOrg' => $name,
					'content' => BufferedView::instance('org/memberlist',
						array(
							'name' => $this->org['name'],
							'description' => $this->org['description'],
							'long_description' => $this->org['long_description'],
							'announcements' => $article,
							'members' => $members
						)
					)->getBuffer()
				);
			}
		}

	}

	public function __destruct() {
		if( $this->templateVars['highlight'] === null ) $this->templateVars['highlight'] = '';
		if( $this->templateVars['currentOrg'] === null ) $this->templateVars['currentOrg'] = '';
		if( $this->iAmBanned ) $this->templateVars['content'] .= '<div style="margin-top: 20px;font-weight: bold">&gt;You have been banned! Some features are disabled from this course. Please look for your professor listed at the course information to fix your account.</div>';
		new View('template',
			array_merge(
				array(
					'globalnav' => new BufferedView('org/globalnav',
						array(
							'isMember' => $this->iAmMember,
							'inboxUnread' => $this->inboxUnread
						)
					),
					'usernav' => new BufferedView('org/usernav',
						array(
							'highlight' => $this->templateVars['highlight'],
							'currentOrg' => $this->templateVars['currentOrg'],
							'isMember' => $this->iAmMember,
							'orgAdmin' => $this->iAmAdmin
						)
					),
					'style' => $this->org[0]['css']
				),
				$this->templateVars
			)
		);
	}

}
